﻿using System;
using System.Data.Entity;
using FollowMe.Model;

namespace FollowMe.Repository
{
    /// <summary>
    /// This is the DBContext, database connection for code first.
    // This is where the DB is defined, created based on models.
    /// </summary>
    public class FMContext : DbContext, IContext
    {
        //Are DBSets, the tables in the DB
        public DbSet<Friend> friends { get; set; }
        public DbSet<Location> locations { get; set; }
        public DbSet<Message> messages { get; set; }
        public DbSet<Member> members { get; set; }
        public DbSet<RegistrationID> registrationIDs { get; set; }

        public IDbSet<TEntity> getSet<TEntity>() where TEntity : class
        {
            return this.Set<TEntity>();
        }

        public void markModified<TEntity>(TEntity entity) where TEntity : class 
        {
            this.Entry(entity).State = EntityState.Modified;
        }

        public void markDeleted<TEntity>(TEntity entity) where TEntity : class
        {
            if (this.Entry(entity).State == EntityState.Detached)
            {
                this.getSet<TEntity>().Attach(entity);
            }
            this.getSet<TEntity>().Remove(entity);
        }

        public Boolean isDetached<TEntity>(TEntity entity) where TEntity : class
        {
            return this.Entry(entity).State == EntityState.Detached;
        }

        /// <summary>
        /// Called when [model creating].
        /// </summary>
        /// <param name="modelBuilder">The model builder.</param>
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

            //These define many:many relationships
            //We do not want to cascade on deletion of those entities!
            modelBuilder.Entity<Friend>()
                .HasRequired<Member>(i => i.MemberAdding)
                .WithMany(i => i.FriendsIAdded)
                .HasForeignKey(u => u.MemberAddingID)
                .WillCascadeOnDelete(false);

            modelBuilder.Entity<Friend>()
                .HasRequired(i => i.FriendAdded)
                .WithMany(i => i.FriendsThatAddedMe)
                .HasForeignKey(u => u.FriendAddedID)
                .WillCascadeOnDelete(false);


            modelBuilder.Entity<Message>()
                .HasRequired<Member>(i => i.MessageSender)
                .WithMany(i => i.MessagesSent)
                .HasForeignKey(u => u.MessageSenderId)
                .WillCascadeOnDelete(false);

            modelBuilder.Entity<Message>()
               .HasRequired<Member>(i => i.MessageReceiver)
               .WithMany(i => i.MessagesReceived)
               .HasForeignKey(u => u.MessageReceiverId)
               .WillCascadeOnDelete(false);

            
            base.OnModelCreating(modelBuilder);
        }

    }
}
